import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_address_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_address/enterprise_address_list_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_overall_location/user_overall_location.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bean/binding_terminal_edit_upload_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/binding_terminal_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_dialog_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

/// 绑定成功提示弹窗
class TerminalBindSuccessDialog extends StatefulWidget {

  final int rcaid;
  final String hsn;
  final String terminalName;
  final String position;

  const TerminalBindSuccessDialog(this.rcaid, this.hsn,
      this.terminalName, this.position);

  ///跳转
  static Future<bool> navigatorPushDialog(BuildContext context, int rcaid,String hsn, String terminalName, String position, RouteSettings routeSettings) {
    return VgDialogUtils.showCommonDialog(
        context: context,
        child: TerminalBindSuccessDialog(rcaid, hsn, terminalName, position),
        barrierDismissible: false,
        routeSettings: routeSettings,
);
  }

  @override
  _TerminalBindSuccessDialogState createState() =>
      _TerminalBindSuccessDialogState();
}

class _TerminalBindSuccessDialogState extends BaseState<TerminalBindSuccessDialog>{
  ///名字编辑控制器
  TextEditingController _nameEditingController;

  ///摆放位置编辑控制器
  TextEditingController _positionEditingController;

  CompanyAddressListInfoBean addBean = CompanyAddressListInfoBean();

  BindingTermialEditUploadBean _uploadBean;

  NewTerminalListViewModel _viewModel;

  UserOverallLocationUtil userOverallLocationUtil;

  VgLocation _locationPlugin;
  CompanyAddressListInfoBean addressBean;

  String gps;

  @override
  void initState() {
    super.initState();
    userOverallLocationUtil = UserOverallLocationUtil(this);
    userOverallLocationUtil?.valueNotifier?.addListener(() {
      setState(() {
        addressBean = CompanyAddressListInfoBean();
        if((userOverallLocationUtil?.valueNotifier?.value?.length??0)<1)return;
        addressBean =  userOverallLocationUtil?.valueNotifier?.value[0];
        _positionEditingController?.text = addressBean?.address;
        _uploadBean?.caid = addressBean?.caid;
      });
    });
    _uploadBean = BindingTermialEditUploadBean();
    _uploadBean
      ..flg = "00"
      ..terminal_name = widget?.terminalName
      ..rcaid = widget?.rcaid
      ..hsn = widget?.hsn
      ..position = widget?.position;

    _nameEditingController = TextEditingController()
      ..addListener(() => _notifyEditsChange())
      ..text = widget?.terminalName;
    _positionEditingController = TextEditingController(text: "")
      ..addListener(() => _notifyEditsChange())
      ..text = widget?.position;
    _viewModel = NewTerminalListViewModel(this);
    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocation((value) {
      Future<String> latlng = VgLocationUtils.getCacheLatLngString();
      latlng.then((value){
        gps = value;
        userOverallLocationUtil.userLocationInfoGps(value);
      });
    });
    _notifyEditsChange();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 33),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: ThemeRepository.getInstance().getCardBgColor_21263C()),
          child: _toMainColumnWidget(context),
        ),
      ),
    );
  }
  ///通知编辑框更新
  _notifyEditsChange() {
    _uploadBean
      ..terminal_name = _nameEditingController?.text?.trim()
      ..position = _positionEditingController?.text?.trim();
    setState(() { });
  }

  Widget _toMainColumnWidget(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        SizedBox(
          height: 32,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              "images/icon_bind_success.png",
              width: 30,
            ),
            SizedBox(width: 8,),
            Text(
              "绑定成功",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                  fontSize: 18,
                  fontWeight: FontWeight.w600),
            ),
          ],
        ),
        SizedBox(
          height: 25,
        ),
        _toNameSettingWidget(),
        SizedBox(
          height: 15,
        ),
        _toPositionSettingWidget(),
        SizedBox(
          height: 20,
        ),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: (){
            if(!(_uploadBean?.isAlive() ?? false)){
              VgToastUtils.toast(context, _uploadBean?.checkVerify());
              return;
            }
            String msg =_uploadBean?.checkVerify();
            if(StringUtils.isEmpty(msg)){
              _viewModel?.toSaveTerminalInfo(context, _uploadBean, callback: (){
                RouterUtils.pop(context, result: true);
              });
              return;
            }
            VgToastUtils.toast(context, msg);
            // RouterUtils.popUntil(AppMain.context, AppMain.ROUTER,rootNavigator: false);
          },
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 20),
            height: 40,
            decoration: BoxDecoration(
                color: (_uploadBean?.isAlive() ?? false)?
                ThemeRepository.getInstance().getPrimaryColor_1890FF()
                    :ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
                borderRadius: BorderRadius.circular(22.5)),
            child: Center(
              child: Text(
                "确定",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: Colors.white, fontSize: 16, height: 1.2),
              ),
            ),
          ),
        ),
        SizedBox(
          height: 30,
        )
      ],
    );
  }

  ///设备名称
  Widget _toNameSettingWidget() {
    return Container(
      height: 45,
      margin: EdgeInsets.symmetric(horizontal: 15),
      padding: EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      ),
      child: Row(
        children: <Widget>[
          Container(
            width: 71,
            alignment: Alignment.centerLeft,
            child: Text(
              "设备名称",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                  color: ThemeRepository.getInstance()
                      .getTextMinorGreyColor_808388(),
                  fontSize: 14,
                  height: 1.2),
            ),
          ),
          Expanded(
            child: VgTextField(
              controller: _nameEditingController,
              maxLines: 1,
              maxLimitLength: 10,
              limitCallback: (int maxLimitLength) {
                VgToastUtils.toast(context, "最多${maxLimitLength ?? 0}个字～");
              },
              scrollPhysics: BouncingScrollPhysics(),
              decoration: InputDecoration(
                border: InputBorder.none,
                contentPadding: const EdgeInsets.only(bottom: 2),
                hintText: "请输入（10个字以内）" ?? "",
                hintStyle: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getTextEditHintColor_3A3F50(),
                    fontSize: 14),
              ),
              style: TextStyle(
                  fontSize: 14,
                  color:
                  ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
            ),
          )
        ],
      ),
    );
  }


  ///摆放位置设置
  Widget _toPositionSettingWidget() {
    return GestureDetector(
      onTap: (){
        EnterpriseAddressListPage.navigatorPush(context,gps).then((value){
          addBean = value;
          _uploadBean?.caid = addBean?.caid;
          _positionEditingController?.text = addBean?.address;
          setState(() { });
        });
      },
      child: Container(
        height: 45,
        margin: EdgeInsets.symmetric(horizontal: 15),
        padding: EdgeInsets.symmetric(horizontal: 15),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        ),
        child: Row(
          children: <Widget>[
            Container(
              width: 71,
              alignment: Alignment.centerLeft,
              child: Text(
                "摆放位置",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getTextMinorGreyColor_808388(),
                    fontSize: 14,
                    height: 1.2),
              ),
            ),
            Expanded(
              child: Text(
                _positionEditingController?.text?.trim() ?? "请选择",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: _positionEditingController?.text?.trim()?.isNotEmpty
                      ? ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                      : ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
                  fontSize: 14,
                ),
              ),
            ),
            Image.asset(
              "images/index_arrow_ico.png",
              width: 6,
            ),
            // Expanded(
            //   child: VgTextField(
            //     controller: _positionEditingController,
            //     minLines: 1,
            //     maxLines: 2,
            //     // maxLimitLength: 10,
            //     // limitCallback: (int maxLimitLength){
            //     //   VgToastUtils.toast(context, "最多${maxLimitLength ?? 0}个字～");
            //     // },
            //     scrollPhysics: BouncingScrollPhysics(),
            //     decoration: InputDecoration(
            //       border: InputBorder.none,
            //       contentPadding: const EdgeInsets.only(bottom: 2),
            //       hintText: "请输入" ?? "",
            //       hintStyle: TextStyle(
            //           color: ThemeRepository.getInstance()
            //               .getTextEditHintColor_3A3F50(),
            //           fontSize: 14),
            //     ),
            //     style: TextStyle(
            //         fontSize: 14,
            //         height: 1.2,
            //         color:
            //         ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
            //   ),
            // ),
          ],
        ),
      ),
    );
  }
}


